package com.conversationboard.model;

import java.awt.image.BufferedImage;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import com.conversationboard.database.Database;
import com.conversationboard.database.Queries;

public class PollResults {

    private BufferedImage chart;
    private List<PollResult> results = new LinkedList<PollResult>();


    public List<PollResult> getResults() {
        return results;
    }


    private void populate(int boardId, int threadId) throws SQLException {

        Connection connection = Database.getConnection();

        try {
            PreparedStatement statement = connection.prepareStatement(Queries.GET_POLL_RESULTS);
            statement.setInt(1, boardId);
            statement.setInt(2, threadId);

            statement.execute();

            ResultSet resultSet = statement.getResultSet();

            while (resultSet.next()) {

                String optionText = resultSet.getString("optiontext");
                int voteCount = resultSet.getInt("votecount");

                PollResult pollResult = new PollResult();
                pollResult.setOptionText(optionText);
                pollResult.setVoteCount(voteCount);

                results.add(pollResult);
            }

            statement.close();

        } finally {
            Database.close(connection);
        }

    }


    public PollResults(int boardId, int threadId) throws SQLException {

        this.populate(boardId, threadId);

    }


    public BufferedImage getChart() {
        return chart;
    }


    public void setChart(BufferedImage chart) {
        this.chart = chart;
    }

}
